const startBtn = document.getElementById('start');
const hourDisplay = document.getElementById('hourDisplay');
const minDisplay = document.getElementById('minDisplay');
const secDisplay = document.getElementById('secDisplay');
const hourIpt = document.getElementById('hourIpt');
const minIpt = document.getElementById('minIpt');
const secIpt = document.getElementById('secIpt');
const sound = new Audio('alarm.mp3');
let timer;

function subHour() {
    console.log('subHour');
    hour = hourDisplay.innerText;
    hour = hour[0] == "0" ? hour[1] : hour;
    if (hour != "0") {
        hourDisplay.innerText = String(--hour)
        minDisplay.innerText = '59';
    }
}

function subMin() {
    console.log('subMin');
    min = minDisplay.innerText;
    min = min[0] == "0" ? min[1] : min;
    if (min == "0") {
        subHour();
    }else{
        min = String(--min)
        minDisplay.innerText = min.length < 2 ? '0'+min : min;
        secDisplay.innerText = '59';
    }
}

function subSec() {
    console.log('subSec');
    sec = secDisplay.innerText;
    sec = sec[0] == "0" ? sec[1] : sec;
    if (sec == "0") {
        subMin();
    }else{
        sec = String(--sec)
        secDisplay.innerText = sec.length < 2 ? '0'+sec : sec;
    }
}

function stop(){
    console.log('stop');
}

function tick(){
    console.log('tick');
    hour = hourDisplay.innerText;
    min = minDisplay.innerText;
    sec = secDisplay.innerText;
    hour = hour[0] == "0" ? hour[1] : hour;
    min = min[0] == "0" ? min[1] : min;
    sec = sec[0] == "0" ? sec[1] : sec;
    if(sec == 0 && min == 0 && hour == 0) {
        sound.play();
        stop();
    }else{
        subSec();
    }
}

function start() {
    console.log('start');
    startBtn.innerText = '停止计时';
    startBtn.removeEventListener('click', start);
    startBtn.addEventListener('click', stop);
    hourValue = hourIpt.value;
    minValue = minIpt.value;
    secValue = secIpt.value;
    hourDisplay.innerText = hourValue.length < 2 ? '0'+hourValue : hourValue;
    minDisplay.innerText = minValue.length < 2 ? '0'+minValue : minValue;
    secDisplay.innerText = secValue.length < 2 ? '0'+secValue : secValue;
    timer = setInterval(tick, 1000);
}

function stop() {
    console.log('stop');
    startBtn.innerText = '开始计时';
    startBtn.removeEventListener('click', stop);
    startBtn.addEventListener('click', start);
    clearInterval(timer);
}

startBtn.addEventListener('click', start);